<template>

    <div class=" w-[50%] mx-auto bg-gray-100 p-4 rounded-md p-4">
        <a-form :model="formState" :rules="rules"  @finish="onFinish" v-bind="layout">
            <a-form-item label="配置标题" name="title">
                <a-input v-model:value="formState.title" placeholder="请输入配置标题" />
            </a-form-item>
            <a-form-item label="配置唯一标识" name="name">
                <a-input v-model:value="formState.name" placeholder="请输入配置唯一标识" />
            </a-form-item>
            <a-row :gutter="2">
                <a-col :span="12">
                    <a-form-item label="配置组" name="group_id">
                        <a-input-group compact>
                            <a-select allow-clear v-model:value="formState.group_id" class="w-[50%]"
                                placeholder="请选择配置组">
                                <a-select-option :value="item.id" v-for="item in systemConfigList?.lists || []"
                                    :key="item.id">{{
                                        item.title }}</a-select-option>
                            </a-select>
                            <a-button type="primary" @click="() => GroupRef?.open()">新增组</a-button>
                        </a-input-group>
                        <add-group ref="GroupRef" @success="emit('success')" />
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item label="配置内容" name="input">
                        <a-select v-model:value="formState.input" class="w-[50%]" placeholder="请选择配置内容"
                            @change="handleChange">
                            <a-select-option value="input">文本</a-select-option>
                            <a-select-option value="textarea">多行文本</a-select-option>
                            <a-select-option value="number">数字</a-select-option>
                            <a-select-option value="boolean">布尔</a-select-option>
                            <a-select-option value="array">数组</a-select-option>
                            <a-select-option value="object">对象</a-select-option>
                            <a-select-option value="json">json</a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>
            </a-row>
            <a-form-item label="配置"
                v-if="formState.input === 'input' || formState.input === 'textarea' || formState.input === 'number' || formState.input === 'boolean'"
                name="value">
                <a-input v-model:value="formState.value" v-if="formState.input === 'input'" placeholder="请输入配置值" />
                <a-textarea v-model:value="formState.value" v-if="formState.input === 'textarea'"
                    placeholder="请输入配置值" />
                <a-input-number v-model:value="formState.value" v-if="formState.input === 'number'"
                    placeholder="请输入配置值" />
                <a-switch v-model:value="formState.value" v-if="formState.input === 'boolean'" placeholder="请输入配置值" />
            </a-form-item>
            <div v-if="(formState.input === 'object' || formState.input === 'json') && Array.isArray(formState.value)"
                class="mt-4">
                <a-row v-for="(item, idx) in formState.value as KeyValueItem[]" :key="idx" type="flex" align="middle">
                    <a-col :span="10">
                        <a-form-item :label="'Key'" :name="['value', idx, 'key']" :rules="[
                            { required: true, message: 'Key不能为空' },
                            {
                                validator: (rule: any, value: string) => {
                                    const arr = formState.value as KeyValueItem[];
                                    const repeat = arr.filter((v, i) => v.key === value && i !== idx);
                                    if (repeat.length > 0) return Promise.reject('Key不能重复');
                                    return Promise.resolve();
                                }
                            }
                        ]">
                            <a-input v-model:value="item.key" placeholder="请输入配置key" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="10">
                        <a-form-item :label="'Value'" :name="['value', idx, 'value']"
                            :rules="[{ required: true, message: 'Value不能为空' }]">
                            <a-input v-model:value="item.value" placeholder="请输入配置值" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="4" style="display: flex; align-items: center;">
                        <a-button @click="removeKeyValue(idx)" danger class="mb-6 ml-2">删除</a-button>
                    </a-col>
                </a-row>
                <a-button class="mt-2" type="dashed" block @click="addKeyValue">+ 新增一行</a-button>

            </div>


            <a-form-item :wrapper-col="{ ...layout.wrapperCol, offset: 8 } " class="mt-4">
                <a-button type="primary" html-type="submit">提交</a-button>
            </a-form-item>
        </a-form>
    </div>

</template>
<script setup lang="ts">
import addGroup from './addGroup.vue'
import { addSystemConfig } from '@/api/system/system'
const GroupRef = ref<InstanceType<typeof addGroup>>()
const emit = defineEmits<{
    (e: 'success'): void
}>()

const layout = {
    labelCol: { span:0 },
    wrapperCol: { span: 24 },
};

const props = defineProps<{
    systemConfigList: any
}>()
const Promise = window.Promise


interface KeyValueItem {
    key: string
    value: string
}
interface FormState {
    title: string
    name: string
    group_id: number | null
    input: string
    value: string | KeyValueItem[]
}
const formState = reactive<FormState>({
    title: '',
    name: '',
    group_id: null,
    input: 'input',
    value: ''
})
const rules = {
    title: [{ required: true, message: '请输入配置标题' }],
    name: [
        { required: true, message: '请输入配置唯一标识' },
        { pattern: /^[a-zA-Z_]+$/, message: '标识只能包含大小写字母和下划线' }
    ],
    group_id: [{ required: true, message: '请选择配置组' }],
    input: [{ required: true, message: '请选择配置内容' }],
    value: [{ required: true, message: '请输入配置值' }]
}


const handleChange = (value: string) => {
    if (value === 'object' || value === 'json') {
        formState.value = [{ key: '', value: '' }]
    } else {
        formState.value = ''
    }
}

function addKeyValue() {
    if (Array.isArray(formState.value)) {
        formState.value.push({ key: '', value: '' })
    }
}
function removeKeyValue(idx: number) {
    if (Array.isArray(formState.value)) {
        formState.value.splice(idx, 1)
    }
}

const onFinish = async (values: any) => {
    const res = await addSystemConfig(values)
    emit('success')
}
</script>